﻿/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF WIKIX.
WIKIX IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

WIKIX IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH WIKIX. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.PlugIn;
using System.Threading;
using EPiServer.Web;
using System.Web.Routing;
using EPiServer.Security;

namespace EPiServer.Research.Wiki.Core
{
    public class WikiInit : PlugInAttribute
    {
        
        public static void Start()
        {
            //Load All wiki's, Build dictionary of wiki names (in seperate thread)
            EPiServer.Web.InitializationModule.FirstBeginRequest += new EventHandler(InitializationModule_FirstBeginRequest);

              
            //TODO: Do threaded. ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o) { }));
            WikiManager.Instance.Initialize(); 
            

            //Attach rewriting
            HtmlRewriteToExternal.HtmlRewriteInit += new EventHandler<HtmlRewriteEventArgs>(HtmlRewriteToExternal_HtmlRewriteInit);


            //Hide Wiki elements from edit-mode
            DataFactory.Instance.FinishedLoadingChildren += new ChildrenEventHandler(Instance_FinishedLoadingChildren);


        }

        static void InitializationModule_FirstBeginRequest(object sender, EventArgs e)
        {
            WikiManager.Instance.InitRootWikis();
        }

        /// <summary>
        /// Can hide wiki elements from edit-mode
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Instance_FinishedLoadingChildren(object sender, ChildrenEventArgs e)
        {
            string s = EPiServer.Configuration.Settings.Instance.UIUrl.ToString();
            if (HttpContext.Current == null) return;
            if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith(s.ToLower()))
            {
                if (DataFactory.Instance.GetPage(e.PageLink).PageTypeName.StartsWith("[Wiki]"))
                {
                    PageData root = WikiManager.Instance.GetWikiRoot(e.PageLink);
                    bool removeArticles = !(root["HideArticles"]==null);
                    bool removeSections = !(root["HideSections"] == null);
                    bool removeComments = !(root["HideComments"] == null);
                    if (removeArticles || removeSections || removeComments)
                    {
                        for (int i = e.Children.Count - 1; i >= 0; i--)
                        {
                            if(
                                ((e.Children[i].PageTypeName==WikiManager.WIKIARTICLENAME) && removeArticles) ||
                                ((e.Children[i].PageTypeName==WikiManager.WIKISECTIONNAME) && removeSections) ||
                                ((e.Children[i].PageTypeName==WikiManager.WIKIDISCUSSIONNAME) && removeComments)
                                ){
                                    e.Children.RemoveAt(i);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Initialize html rewriting to create links on the fly
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void HtmlRewriteToExternal_HtmlRewriteInit(object sender, HtmlRewriteEventArgs e)
        {
            WikiRewrite reWriter = new WikiRewrite();
            e.RewritePipe.HtmlRewriteValue += reWriter.HtmlRewriteValueEventHandler;
            e.RewritePipe.HtmlRewriteName += reWriter.HtmlRewriteNameEventHandler;
        }
    }
}
